#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "include/MQTTAsync.h"


#define ADDRESS     "mqtt://broker.emqx.io:1883"
#define CLIENTID    "ExampleClientSub"
#define TOPIC       "MQTT Examples"
#define PAYLOAD     "Hello World!"
#define QOS         1
#define TIMEOUT     10000L
volatile MQTTAsync_token deliveredtoken;
int disc_finished = 0;
int subscribed = 0;
int finished = 0;



int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
{
    int i;
    char* payloadptr;
    printf("Message arrived\n");
    printf("     topic: %s\n", topicName);
    printf("   message: ");
    payloadptr = message->payload;
    for(i=0; i<message->payloadlen; i++)
    {
        putchar(*payloadptr++);
    }
    putchar('\n');
    MQTTAsync_freeMessage(&message);
    MQTTAsync_free(topicName);
    return 1;
}

void onSubscribe(void* context, MQTTAsync_successData* response)
{
        printf("Subscribe succeeded\n");
        subscribed = 1;
}
void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
        printf("Subscribe failed, rc %d\n", response ? response->code : 0);
        finished = 1;
}


void onDisconnect(void* context, MQTTAsync_successData* response)
{
        printf("Successful disconnection\n");
}

void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
        printf("Connect failed: %s\n", response->message);
}

void onConnect(void* context, MQTTAsync_successData* response)
{
        printf("onConnect success....\n");
}

void connlost(void *context, char *cause)
{
        printf("connlost ....\n");

        int rc;
        MQTTAsync client = (MQTTAsync)context;


        MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
        conn_opts.connectTimeout = 10;
        conn_opts.automaticReconnect = 1;
        conn_opts.minRetryInterval = 1;
        conn_opts.maxRetryInterval = 10;

        conn_opts.keepAliveInterval = 10;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = onConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = client;

        if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start connect, return code %d\n", rc);
                exit(-1);
        }

        printf("connlost end ....\n");
}


int main(int argc, char* argv[])
{
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        MQTTAsync_token token;
        int rc;
        

        MQTTAsync client;
        MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
        MQTTAsync_setCallbacks(client, client, connlost, msgarrvd, NULL);

        MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
        conn_opts.connectTimeout = 10;
        conn_opts.automaticReconnect = 1;
        conn_opts.minRetryInterval = 1;
        conn_opts.maxRetryInterval = 10;

        conn_opts.keepAliveInterval = 10;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = onConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = client;

        if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start connect, return code %d\n", rc);
                exit(-1);
        }
        printf("MQTTAsync_connect.....\n");


        sleep(20);
        
        MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
        opts.onSuccess = onSubscribe;
        opts.onFailure = onSubscribeFailure;
        opts.context = client;
        deliveredtoken = 0;

        if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start subscribe, return code %d\n", rc);
        }else{
                printf("success to start subscribe, return code %d\n", rc);
        }
        printf("---------1-----\n");

        while(1){
                sleep(10);
        }
       
        MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
        disc_opts.onSuccess = onDisconnect;
        if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start disconnect, return code %d\n", rc);
        }

        
               
        MQTTAsync_destroy(&client);
        return rc;
}